<?php

namespace app\v1\controller;

use app\v1\model\MiniOrder;
use think\Db;
use think\facade\Log;
use think\response\Json;

class Callback extends BaseController
{
    /**
     * 抖音支付回调
     * 抖音支付只有支付成功会回调，故该处接收到回调则默认处理订单支付成功
     * @return Json
     */
    public function dyPay(): Json
    {
        $param = request()->param();
        Log::write(json_encode($param));
        if ($param['type'] == 'payment') {
            $msg = json_decode($param['msg'], true);
            $order_number = $msg['cp_orderno'] ?? ''; // 订单号
            $cp_extra = $msg['cp_extra'] ?? ''; // 发起支付传入的参数
            $way = $msg['way'] ?? ''; // 支付方式 1-微信支付，2-支付宝支付，10-抖音支付
            $pay_type = '微信支付';
            if ($way == 2) {
                $pay_type = '支付宝支付';
            } else if ($way == 10) {
                $pay_type = '抖音支付';
            }
            $total_amount = $msg['total_amount'] ?? 0; // 支付金额(分)

            $update = [
                'order_status' => 1,
                'pay_type' => $pay_type,
                'channel_no' => $msg['channel_no'] ?? '',
                'payment_order_no' => $msg['payment_order_no'] ?? '',
                'pay_money' => bcdiv($total_amount, 100, 2),
                'pay_time' => $msg['paid_at'] ?? time()
            ];

            Db::startTrans();
            try {
                $order = (new MiniOrder())->where('order_number', $order_number)->find();
                if (!$order) {
                    Log::write("未找到对应订单，订单号{$order_number}", 'error');
                    return json(['err_no' => 1, 'err_tips' => '未找到对应订单']);
                }
                $order->save($update);
                Log::write("订单号：{$order_number}，回调修改信息" . json_encode($update));
                Db::commit();
                return json(['err_no' => 0, 'err_tips' => 'success']);
            } catch (\Throwable $t) {
                Db::rollback();
                Log::write("回调处理失败：" . json_encode([$t->getFile(), $t->getLine(), $t->getMessage()]));
                return json(['err_no' => 1, 'err_tips' => '回调处理失败']);
            }
        }
        return json(['err_no' => 0, 'err_tips' => 'success']);
    }
}